import { Request, Response } from 'express';
import { asyncHandler, ApiError } from '../middlewares/errorHandler';
import prisma from '../config/database';
import multer from 'multer';
import path from 'path';
import fs from 'fs';

// 配置文件上传
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    const uploadDir = 'uploads/avatars';
    if (!fs.existsSync(uploadDir)) {
      fs.mkdirSync(uploadDir, { recursive: true });
    }
    cb(null, uploadDir);
  },
  filename: (req, file, cb) => {
    const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1e9);
    cb(null, 'avatar-' + uniqueSuffix + path.extname(file.originalname));
  },
});

const upload = multer({
  storage,
  limits: { fileSize: 5 * 1024 * 1024 }, // 5MB
  fileFilter: (req, file, cb) => {
    const allowedTypes = /jpeg|jpg|png|gif/;
    const extname = allowedTypes.test(path.extname(file.originalname).toLowerCase());
    const mimetype = allowedTypes.test(file.mimetype);

    if (mimetype && extname) {
      return cb(null, true);
    } else {
      cb(new Error('Only image files are allowed!'));
    }
  },
});

// 获取用户资料
export const getUserProfile = asyncHandler(async (req: Request, res: Response) => {
  const userId = req.user!.userId;

  const user = await prisma.user.findUnique({
    where: { id: userId },
    include: {
      profile: true,
    },
  });

  if (!user) {
    throw new ApiError(404, 'User not found');
  }

  res.json({
    code: 200,
    message: 'Success',
    data: user,
  });
});

// 更新用户资料
export const updateUserProfile = asyncHandler(async (req: Request, res: Response) => {
  const userId = req.user!.userId;
  const { fullName, phone, bio, education, occupation, birthday } = req.body;

  const profile = await prisma.userProfile.update({
    where: { userId },
    data: {
      fullName,
      phone,
      bio,
      education,
      occupation,
      birthday: birthday ? new Date(birthday) : undefined,
    },
  });

  res.json({
    code: 200,
    message: 'Profile updated successfully',
    data: profile,
  });
});

// 上传头像
export const uploadAvatar = [
  upload.single('avatar'),
  asyncHandler(async (req: Request, res: Response) => {
    const userId = req.user!.userId;

    if (!req.file) {
      throw new ApiError(400, 'No file uploaded');
    }

    const avatarUrl = `/uploads/avatars/${req.file.filename}`;

    const user = await prisma.user.update({
      where: { id: userId },
      data: { avatar: avatarUrl },
    });

    res.json({
      code: 200,
      message: 'Avatar uploaded successfully',
      data: { avatar: user.avatar },
    });
  }),
];
